import wepy from 'wepy'
import '@/baseAPI.js'

export default class extends wepy.mixin {
  config = {}
  data = {
    searchStr: '',
    // 搜索建议列表
    qsearch: [],
    // 搜索历史记录
    searchHistory: []
  }
  methods = {
    // 搜索事件
    onSearch() {
      if (this.searchStr.length <= 0) {
        return
      }
      if (this.searchHistory.indexOf(this.searchStr) === -1) {
        this.searchHistory.unshift(this.searchStr)
        this.searchHistory = this.searchHistory.splice(0, 10)
        wepy.setStorageSync('kw', this.searchHistory)
      }
      // [ "k", "j", "i", "h", "g", "f", "e","c", "b","a"]

      wepy.navigateTo({ url: '/pages/goods_list?query=' + this.searchStr })
    },
    // 点击历史记录搜索
    tagSearch(searchStr) {
      this.searchStr = searchStr
      wepy.navigateTo({ url: '/pages/goods_list?query=' + this.searchStr })
    },
    // 取消事件
    onCancel() {
      this.qsearch = []
    },
    // 搜索内容改变
    async onChange(e) {
      const kw = e.detail.trim()
      this.searchStr = kw
      if (kw.length <= 0) {
        this.qsearch = []
        return
      }
      const { data: res } = await wepy.get('/goods/qsearch', { query: kw })
      if (res.meta.status !== 200) {
        return wepy.baseToast(res.meta.msg)
      }
      this.qsearch = res.message
      this.$apply()
    },
    // 跳转到商品详情
    goGoodsDetail(goods_id) {
      wepy.navigateTo({ url: '/pages/goods_detail/main?goods_id=' + goods_id });
    },
    // 清除历史记录
    clearHistory() {
      // wepy.setStorageSync('kw', ["ab","aaa","123","abc","a\\","b","a","保温杯","k","j"])
      this.searchHistory = []
      this.$apply()
      wepy.clearStorageSync()
    },
  }

  computed = {
    isShowHistory() {
      if (this.searchStr.trim().length <= 0) {
        return false
      }
      return true
    }
  }

  onLoad() {
    this.searchHistory = wepy.getStorageSync('kw') || []
  }
}